/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rationalsheet.parser.expression;

import java.util.ArrayList;

/**
 *
 * @author Overmind
 */
public class Delim
    implements Comparable<Delim>
{   
    private String delim;
    
    public Delim(String delim) 
        throws NullPointerException,
            IllegalArgumentException
    {
        if(delim == null)
        {
            throw new NullPointerException("delim most be not null");
        }
        
        if(delim.isEmpty())
        {
            throw new IllegalArgumentException("delim most be not empty");
        }
        
        this.delim = delim;
    }
    
    public Skope[] getSkopes(String data)
    {
        return getSkopes(data, new ScopeCounter());
    }
    
    public Skope[] getSkopes(String data, ScopeCounter counter) throws NullPointerException
    {
        if(data == null)
        {
            throw new NullPointerException("data most not null");
        }
        
        ArrayList<Skope> skopes = new ArrayList<>();

        for (int i = 0; i < data.length(); ++i)
        {
            char ch = data.charAt(i);

            if (counter.isZero())
            {
                if (data.startsWith(delim, i))
                {
                    skopes.add(new Skope(i, i+delim.length()));
                }
            }

            if (ch == '(')
            {
                counter.increment();
            } 
            else if (ch == ')')
            {
                counter.decremnet();
            }
        }

        //Collections.reverse(skopes);
        Skope[] result = new Skope[skopes.size()];
        return skopes.toArray(result);
    }

    @Override
    public int compareTo(Delim right)
    {
        return delim.compareTo(right.delim);
    }

    @Override
    public String toString()
    {
        return delim;
    }
    
    
}
